<template>
  <div class="profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>
      
      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名">
              <el-input v-model="profileForm.username" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="real_name">
              <el-input v-model="profileForm.real_name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="profileForm.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户角色">
              <el-tag 
                v-for="role in userRoles" 
                :key="role.id" 
                :type="role.code === 'admin' ? 'danger' : 'primary'"
                style="margin-right: 8px;"
              >
                {{ role.name }}
              </el-tag>
              <span v-if="userRoles.length === 0" style="color: #999;">暂无角色</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账户状态">
              <el-tag :type="profileForm.is_active ? 'success' : 'danger'">
                {{ profileForm.is_active ? '正常' : '禁用' }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleUpdate" :loading="loading">
            保存修改
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const profileFormRef = ref()
const loading = ref(false)

const profileForm = reactive({
  username: '',
  email: '',
  real_name: '',
  phone: '',
  avatar: '',
  is_active: true
})

const userRoles = ref([])

const profileRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  real_name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 初始化表单数据
const initForm = () => {
  const userInfo = userStore.userInfo
  if (userInfo) {
    profileForm.username = userInfo.username || ''
    profileForm.email = userInfo.email || ''
    profileForm.real_name = userInfo.real_name || ''
    profileForm.phone = userInfo.phone || ''
    profileForm.avatar = userInfo.avatar || ''
    profileForm.is_active = userInfo.is_active !== undefined ? userInfo.is_active : true
    
    // 设置用户角色
    userRoles.value = userInfo.roles || []
  }
}

// 更新个人资料
const handleUpdate = async () => {
  try {
    await profileFormRef.value.validate()
    loading.value = true
    
    await userStore.updateProfileAction({
      email: profileForm.email,
      real_name: profileForm.real_name,
      phone: profileForm.phone,
      avatar: profileForm.avatar
    })
  } catch (error) {
    console.error('更新失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  profileFormRef.value.resetFields()
  initForm()
}

// 头像上传前的处理
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  
  if (isJPG && isLt2M) {
    // 这里应该上传到服务器，暂时使用本地URL
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      profileForm.avatar = e.target.result
    }
  }
  
  return false // 阻止默认上传
}

onMounted(() => {
  initForm()
})
</script>

<style scoped>
.profile {
  padding: 20px;
}

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}
</style> 